package com.api.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.api.entity.RequestHeader;

public class ApiUtil {
	public static String getAllUrl(HttpServletRequest request){
		String protocol = request.getParameter("protocol");
		String ip = request.getParameter("ip");
		String port = request.getParameter("port");
		if(StringUtils.isBlank(port)){
			port = "80";
		}
		String url = request.getParameter("url");
		//http://127.0.0.1:8080/s/blog_725eee7e01015axt.html
		String allUrl = protocol.trim() + ip.trim() +":"+ port.trim() ;
		if(url.indexOf("/")!=0){
			allUrl = allUrl + "/";
		}
		allUrl = allUrl + url.trim();
		return allUrl;
	}
	public static Boolean isBank_allUrl(HttpServletRequest request){
		String protocol = request.getParameter("protocol");
		String ip = request.getParameter("ip");
		String port = request.getParameter("port");
		if(StringUtils.isBlank(port)){
			port = "80";
		}
		String url = request.getParameter("url");
		return StringUtils.isNotEmpty(url) && StringUtils.isNotEmpty(ip) &&StringUtils.isNotEmpty(port) &&StringUtils.isNotEmpty(protocol);
	}
	private static  List <NameValuePair> convertListNameValuePair(Map<String, String> map){
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		if(map!=null){
			Iterator<String> it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				nvps.add(new BasicNameValuePair(key, map.get(key)));
			}
		}
		return nvps;
	}
	public static HttpJson httpRequest(String url,Map<String, String> queryParas,String method,List<RequestHeader> hederList){
		HttpJson httpJson= new HttpJson();
		try {
			String data = null;
			if("get".equals(method)){
				data = get(url, queryParas, hederList);
			}else{
				data =post(url, queryParas, hederList);
			}
			if(StringUtils.isNotEmpty(data)){
				httpJson.setData(data);
			}
		} catch (Exception e) {
			httpJson.setIsSuccess(false);
			httpJson.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return httpJson;
	};
	private static String post(String url,Map<String, String> queryParas,List<RequestHeader> hederList) throws Exception{
		String entityStr = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
			 HttpPost httpPost = new HttpPost(url);
	         List <NameValuePair> nvps = null;
	         nvps = convertListNameValuePair(queryParas);
	         httpPost.setEntity(new UrlEncodedFormEntity(nvps));
	         
	         if(hederList!=null&&hederList.size()>0){
	        	 for (int i = 0; i < hederList.size(); i++) {
	        		httpPost.addHeader(hederList.get(i).getName(), hederList.get(i).getVal());
				}
	         }
	        
	         
	         CloseableHttpResponse response = httpclient.execute(httpPost);
	
	         try {
	             HttpEntity entity = response.getEntity();
	             entityStr = EntityUtils.toString(entity);
	             EntityUtils.consume(entity);
	         } finally {
	        	 response.close();
	         }
        } finally {
            httpclient.close();
        }
		return entityStr;
	}
	private static String get(String url,Map<String, String> queryParas,List<RequestHeader> hederList) throws Exception{
		String entityStr = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(buildUrlWithQueryString(url, queryParas));
	         if(hederList!=null&&hederList.size()>0){
	        	 for (int i = 0; i < hederList.size(); i++) {
	        		 httpGet.addHeader(hederList.get(i).getName(), hederList.get(i).getVal());
				}
	         }
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {
                HttpEntity entity = response.getEntity();
                entityStr = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            } finally {
            	response.close();
            }
        } finally {
            httpclient.close();
        }
		return entityStr;
	}
	
	
	private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) {
		if (queryParas == null || queryParas.isEmpty())
			return url;
		
		StringBuilder sb = new StringBuilder(url);
		boolean isFirst;
		if (!url.contains("?")) {
			isFirst = true;
			sb.append("?");
		}
		else {
			isFirst = false;
		}
		
		for (Entry<String, String> entry : queryParas.entrySet()) {
			if (isFirst) isFirst = false;	
			else sb.append("&");
			
			String key = entry.getKey();
			String value = entry.getValue();
			if (StringUtils.isNotEmpty(value))
				try {value = URLEncoder.encode(value, "UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}
			sb.append(key).append("=").append(value);
		}
		return sb.toString();
	}
	
	
	
}
